#setwd("/Replication Files")

#Install packages 
install.packages("maps")
install.packages("geosphere")
install.packages("readxl")
install.packages("rworldmap")
install.packages("rworldxtra")
install.packages("network")

install.packages("dplyr")
install.packages("haven")
install.packages("foreign")
install.packages("ergm")
install.packages("btergm")

#Figure 2
library("maps")
library("geosphere")
library("readxl")
library("rworldmap")
library("rworldxtra")
library("network")

nodes <- read_excel("Nodes.xlsx") 
edges <- read_excel("Edges.xlsx")

net <- network(edges,
                    matrix.type = 'edgelist',
                    directed = TRUE)

network.vertex.names(net) <- nodes$ID
set.vertex.attribute(net, attrname = "lon", nodes$longitude)
set.vertex.attribute(net, attrname = "lat", nodes$latitude)
data("countriesLow")
countries <- countriesLow[countriesLow@data$ISO3 != c("GRL", "ATA"),]

plot(countries, col="gray80",  border = "gray80", fill=TRUE, bg="white", lwd=0.5)
plot.network(net,
             new = FALSE, 
             coord = cbind(net%v%"lon", net%v%"lat"), 
             edge.col = 'gray30',
             edge.lwd = 0.1,
             vertex.cex = 0.8,
             vertex.col = 'white',
             vertex.border = "black",
             jitter = FALSE)

#Table 1, M1 (ERGM)
library(dplyr)
library(haven)
library(foreign)
library(readxl)
library(ergm)
library(btergm)

DV <- read_excel("UPR5bi.xlsx")
DV [is.na(DV)] <- 0
DV <- DV[, -1]
DV <- as.matrix(DV)

aid1 <- read_excel("lnoda_m1.xlsx")
aid1 [is.na(aid1)] <- 0
aid1 <- aid1[,-1]

aid2 <- read_excel("lnoda_m2.xlsx")
aid2 [is.na(aid2)] <- 0
aid2 <- aid2[,-1]

ally <- read.csv("allys.csv")
ally [is.na(ally)] <- 0
ally <- ally[, -1]

trade <- read_excel("Trade_new.xlsx")
trade [is.na(trade)] <- 0
trade <- trade[,-1]

region <- read_excel("region.xlsx")
region [is.na(region)] <- 0
region <- region[,-1]

attributes <- read.csv("latentHR_hrc_ip_dem.csv")

DVNet <- network(DV)

set.vertex.attribute(DVNet,names(attributes),attributes)

set.network.attribute(DVNet,"aid1",as.matrix(aid1))
set.network.attribute(DVNet,"aid2",as.matrix(aid2))
set.network.attribute(DVNet,"ally",as.matrix(ally))
set.network.attribute(DVNet,"trade",as.matrix(trade))
set.network.attribute(DVNet,"region",as.matrix(region))

DVNet

#set.seed(11235)
#spec01 <- ergm (DVNet~edges+mutual+istar(2)+gwesp(0.5,fixed=T)+edgecov("region")+edgecov("aid1")+edgecov("aid2")+edgecov("trade")+edgecov("ally")+absdiff("ip")+nodeocov("hrc")+nodeocov("lngdp")+nodeicov("lngdp")+nodeocov("latentHR")+nodeicov("latentHR")+absdiff("dem"))

load("spec01.RData")
summary(spec01)

